<!-- 查询 agent -->
{{ $agentSQL := "* FROM agent WHERE id=? and status=1 order by status desc, sortNo desc" }}

{{ if eq .userType 1}}
  {{ $agentSQL ="* FROM agent WHERE id=? order by sortNo desc" }}
{{end}}

{{ $agent := selectOne "agent" $agentSQL .agentID }}
<!DOCTYPE html>
<html lang="{{locale}}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" document="IE=edge">
    <meta name="viewport" document="width=device-width, initial-scale=1">
    <title>{{$agent.Name}} - MINRAG</title>
    <link rel="stylesheet" href="{{basePath}}css/agent.css" />

</head>
<script>
    const basePath="{{basePath}}";
    const locale="{{locale}}";
</script>

<body>
    <div class="chat-container">
        <!-- 左侧历史聊天记录 -->
        <div class="history-panel">
            <div class="history-header">{{T "Chat History"}}</div>
            <div class="history-list">
                <div class="history-item">{{T "Current Chat"}}</div>
            </div>
        </div>

        <!-- 右侧聊天对话框 -->
        <div class="chat-panel">
            <div class="chat-header">{{$agent.Name}}</div>
            <div class="chat-messages">
                <div class="message ai-message"><p>{{$agent.Welcome}}</p></div>
            </div>
            <div class="chat-input">
                <input type="text" id="chat-input" placeholder='{{T "Send a message to minRAG"}}' />
                <button id="send-btn">{{T "Send"}}</button>
            </div>
        </div>
    </div>
</body>
<script src="{{basePath}}js/jquery-3.7.1.min.js"></script>
<script src="{{basePath}}js/marked.min.js"></script>
<script>
function generateStringID() {
    let randomNum="";
    for (i = 0; i < 9; i++) {
        randomNum=randomNum+""+Math.floor(Math.random()*10)
    }

    // 获取当前时间的纳秒级时间戳
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const milliseconds = String(now.getMilliseconds()).padStart(3, '0');

    // 获取更高精度的时间（纳秒级）
    const performanceNow = performance.now();
    const microseconds = String(Math.floor((performanceNow % 1) * 1000)).padStart(3, '0');
    const nanoseconds = String(Math.floor((performanceNow % 1e-3) * 1e6)).padStart(3, '0');

    // 拼接时间字符串
    const pk = `${year}${month}${day}${hour}${minute}${second}${milliseconds}${microseconds}${nanoseconds}`;

    // 拼接最终的32位字符串
    const result = `${pk}${randomNum}`;
    return result;
}
var roomID=generateStringID();

var oldRoomID=localStorage.getItem("roomID");
if(!!oldRoomID){
    roomID=oldRoomID;
}else{
    localStorage.setItem("roomID", roomID);
}

$(document).ready(function() {
    $('#send-btn').click(function() {
        sendMessage();
    });
    $('#chat-input').keypress(function(e) {
        if (e.which == 13) { // Enter key
            sendMessage();
        }
    });
});

async function fetchSSE(aiMessageId,messageText) {
    let aiMarkdown=""
    try {
        const response = await fetch('{{basePath}}v1/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer {{.agentID}}',
                'Accept': 'text/event-stream',
                'Cache-Control':'no-cache',
                'Connection':'keep-alive',
            },
            body:JSON.stringify({
                "messages": [{"role":"user","content":messageText}],
                "user":roomID,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');

        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                console.log('Stream complete');
                break;
            }

            const chunk = decoder.decode(value, { stream: true });
            const lines=chunk.split("\n\n");
            for (const line of lines) {
                if (!line.startsWith('data: ')) {
                    continue;
                }
                const data = line.substring(6);
                if(data=="[DONE]"){
                    continue;
                }
                aiMarkdown=aiMarkdown+data;
                $("#"+aiMessageId+"_markdown").val(aiMarkdown)
                let dataHtml = marked.parse(aiMarkdown);
                // 移除 <p> 标签
                //dataHtml = dataHtml.replace(/<p>([\s\S]*?)<\/p>/g, '$1');
                document.getElementById(aiMessageId).innerHTML=dataHtml
            }
            
        }
    } catch (error) {
        console.error('Fetch stream failed:', error);
    }
}



function sendMessage() {
    const messageText = $('#chat-input').val().trim();
    if (!!!messageText) {
        return
    }
    const userMessage = $('<div class="message user-message"></div>').text(messageText);
    $('.chat-messages').append(userMessage);
    $('#chat-input').val('');

    const aiMessageId=new Date().getTime()+"_aiMessage"
    const aiMessage = $('<div class="message ai-message" id="'+aiMessageId+'"></div><input type="hidden" id="'+aiMessageId+'_markdown">');
    $('.chat-messages').append(aiMessage);
    $('.chat-messages').scrollTop($('.chat-messages')[0].scrollHeight);

    fetchSSE(aiMessageId,messageText)
  
}
</script>

</html>